

package org.jetnuke.modules.blog;

import java.io.IOException;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.VelocityContext;
import org.jetnuke.common.ActionForward;
import org.jetnuke.common.IAction;
import org.jetnuke.common.IAdminInfo;
import org.jetnuke.common.IModuleInfo;
import org.jetnuke.common.IUserInfo;
import org.jetnuke.dao.BlogCommentDAO;
import org.jetnuke.dao.BlogPostDAO;
import org.jetnuke.dao.DataAccessDriver;
import org.jetnuke.entities.BlogComment;
import org.jetnuke.entities.BlogPost;
import org.jetnuke.servlets.utilities.StringUtils;
import org.jetnuke.util.JetUtil;

public class Trackback implements IAction {
	static String okResponse="<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"+
			"<response>\n"+
			"<error>0</error>\n"+
			"</response>";
	static String errorResponse1=" <?xml version=\"1.0\" encoding=\"utf-8\"?>\n"+
    "<response>\n"+
    "<error>1</error>\n"+
    "<message>";
	static String errorResponse2="</message>\n</response>";
	int id;
	String url,title="",excerpt="",blog_name="";
	
	public ActionForward exec(HttpServletRequest request,
			HttpServletResponse response, VelocityContext vc, IModuleInfo info,
			String op, IUserInfo ui, IAdminInfo ai) throws Exception {
		if(!("POST".equalsIgnoreCase(request.getMethod())))
			return null;
		
		String contentType=request.getContentType();
		if(contentType!=null){
			if(!contentType.toLowerCase().trim().startsWith("application/x-www-form-urlencoded")){
				JetUtil.redirect(vc,response,request.getContextPath()+"");
				return null;
				
			}
		}
//		if(!("application/x-www-form-urlencoded".equalsIgnoreCase(contentType))){
//			return null;
//		}
		if(url==null){
//			 If it doesn't look like a trackback at all...
			JetUtil.redirect(vc,response,request.getContextPath()+"");
			return null;
		}
		response.addHeader("Content-Type","text/xml");
		response.addHeader(" charset","UTF-8");
		
		BlogPostDAO bpm=DataAccessDriver.getInst().newBlogPostDAO();
		BlogPost bp=bpm.retrieveByPK(id);
		if(bp.getID()!=id){
			String error="I really need an ID for this to work.";
			sendErrorMessage(error,response);
			return null;
			
		}
		if(!"open".equals(bp.getPINGSTATUS())){
			String error="Sorry, trackbacks are closed for this item.";
			sendErrorMessage(error,response);
			return null;
		}
		BlogCommentDAO bcm=DataAccessDriver.getInst().newBlogCommentDAO();
		List commentByPostList=bcm.selectByPostID(id);
		Iterator it=commentByPostList.iterator();
		while(it.hasNext()){
			BlogComment bc=(BlogComment)it.next();
			if("trackback".equals(bc.getTYPE())&& url.equals(bc.getAUTHOR_URL())){
				String error="We already have a ping from that URI for this post.";
				sendErrorMessage(error,response);
				return null;
			}
		}
		
		
		BlogComment bc=new BlogComment();
		String ua=request.getHeader("user-agent");
		if(ua==null)
			ua="";
		String ip=request.getRemoteAddr();
		if(ip==null)
			ip="";
		bc.setAUTHOR(blog_name);
		bc.setAGENT(ua);
		
		bc.setAUTHOR_EMAIL("");
		bc.setAUTHOR_IP(ip);
		bc.setAUTHOR_URL(url);
		String comment="<strong>"+title+"</strong><br/>"+excerpt ;
		bc.setCONTENT(comment);
		bc.setDATE(new GregorianCalendar().getTime());
		bc.setPARENT(0);
		bc.setPOST_ID(id);
		bc.setTYPE("trackback");
		int uid=1;
		
		String approved="0";
		//if(uid==bp.getAID())
		approved="1"; //TODO give more flexibility!!
		bc.setAPPROVED(approved);
		bc.setUSER_ID(uid);
		
		bcm.addNew(bc);
		response.getWriter().write(okResponse);
		return null;
	}
	private void sendErrorMessage(String errorMessage, HttpServletResponse response)throws IOException{
		String finalString=errorResponse1+errorMessage+errorResponse2;
		response.getWriter().write(finalString);
		
	}

	public void setBlog_name(String blog_name) {
		this.blog_name =StringUtils.filterText(blog_name,true);
	}
	
	public void setExcerpt(String excerpt) {
		this.excerpt = StringUtils.filterText(excerpt,true);
		if(excerpt.length()>255){
			excerpt=excerpt.substring(0,252)+"...";
		}
	}
	
	public void setId(int id) {
		this.id = id;
	}
	
	public void setTitle(String title) {
		this.title = StringUtils.filterText(title,true);
	}
	
	public void setUrl(String url) {
		this.url = url;
	}

}
